package cn.zglbk.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author ： 猪哥亮
 * @创建时间： 2018/6/13
 * @文件描述：
 */
@Component
public class SpringUtils implements ApplicationContextAware {
    private static ApplicationContext applicationContext;
    private static Logger log = LoggerFactory.getLogger(SpringUtils.class);
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringUtils.applicationContext = applicationContext;
    }
    /**
     * 获取applicationContext
     * @return
     */
    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    /**
     * 通过name获取 Bean.
     * @param name
     * @return
     */
    public static Object getBean(String name){
        try {
            return applicationContext.getBean(name);
        }catch (BeansException e){
            log.error("spring容器中没有id为-->"+name+"<--对应的bean");
            return null;
        }
    }

    /**
     * 通过class获取Bean.
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(Class<T> clazz){
        try {
            return applicationContext.getBean(clazz);
        }catch (BeansException e){
            log.error("spring容器中没有类型为-->"+clazz.getName()+"<--对应的bean");
            return null;
        }
    }

    /**
     * 通过name,以及Clazz返回指定的Bean
     * @param name
     * @param clazz
     * @param <T>
     * @return
     */
    public static <T> T getBean(String name,Class<T> clazz){
        try {
            return (T)applicationContext.getBean(name);
        }catch (BeansException e){
            log.error("spring容器中没有id为-->"+name+"<--和类型为-->"+clazz.getName()+"<--对应的bean");
            return null;
        }
    }
}
